<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 商品审核管理
 *
 * @icon fa fa-check-circle
 */
class ProductAudit extends Backend
{
    protected $model = null;
    protected $searchFields = 'name,merchant_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Product');
    }

    /**
     * 查看审核列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 构建状态筛选下拉选项
            $this->view->assign('statusList', [
                '' => __('全部'),
                '2' => __('待审核'),
            ]);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        // 获取分页参数
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $offset = ($page - 1) * $limit;
        
        // 获取搜索参数
        $searchName = $this->request->get('name', '');
        $searchMerchantId = $this->request->get('merchant_id', '');
        $searchAuditStatus = $this->request->get('audit_status', '');
        
        // 构建查询，查询所有商品审核记录
        $query = Db::name('product')
            ->alias('p')
            ->join('merchant m', 'p.merchant_id = m.id', 'LEFT')
            ->join('merchant_audit ma', 'p.merchant_id = ma.merchant_id', 'LEFT')
            ->join('product_category c', 'p.category_id = c.id', 'LEFT')
            ->join('admin a', 'p.auditor_id = a.id', 'LEFT')
            ->field('p.*, p.merchant_id as merchant_id, c.name as category_name, a.username as auditor, ma.store_name as merchant_name');
        
        // 处理搜索条件
        if (!empty($searchName)) {
            $query->where('p.name', 'like', '%' . $searchName . '%');
        }
        if (!empty($searchMerchantId)) {
            $query->where('p.merchant_id', $searchMerchantId);
        }
        if ($searchAuditStatus !== '') {
            $query->where('p.audit_status', intval($searchAuditStatus));
        }
        
        // 获取总数 - 使用子查询避免join导致的count问题
        $countQuery = Db::name('product')->alias('p');
        if (!empty($searchName)) {
            $countQuery->where('p.name', 'like', '%' . $searchName . '%');
        }
        if (!empty($searchMerchantId)) {
            $countQuery->where('p.merchant_id', $searchMerchantId);
        }
        if ($searchAuditStatus !== '') {
            $countQuery->where('p.audit_status', intval($searchAuditStatus));
        }
        $total = $countQuery->count();
        
        // 分页查询
        $list = $query->order('p.id', 'desc')
            ->limit($offset, $limit)
            ->select();
        
        // 处理数据
        foreach ($list as &$row) {
            $row['createtime'] = $row['createtime'] ? date('Y-m-d H:i:s', $row['createtime']) : '';
            $row['updatetime'] = $row['updatetime'] ? date('Y-m-d H:i:s', $row['updatetime']) : '';
            $row['audit_time'] = $row['audit_time'] ? date('Y-m-d H:i:s', $row['audit_time']) : '';
            
            // 设置状态文本
            switch ($row['audit_status']) {
                case 0:
                    $row['status_text'] = '审核未通过';
                    break;
                case 1:
                    $row['status_text'] = '审核通过';
                    break;
                case 2:
                    $row['status_text'] = '待审核';
                    break;
                default:
                    $row['status_text'] = '未知状态';
            }
            
            // 构造category对象
            $row['category'] = [
                'name' => $row['category_name']
            ];
        }

        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = Db::name('product')
            ->alias('p')
            ->join('merchant m', 'p.merchant_id = m.id', 'LEFT')
            ->join('merchant_audit ma', 'm.id = ma.merchant_id', 'LEFT')
            ->join('product_category c', 'p.category_id = c.id', 'LEFT')
            ->field('p.*, p.merchant_id as merchant_id, c.name as category_name, ma.store_name as merchant_store_name')
            ->where('p.id', $ids)
            ->find();
            
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取商品图片
        $productImage = Db::name('product_image')
            ->where('product_id', $ids)
            ->where('image_type', 1) // 1为商品轮播图
            ->order('sort asc')
            ->find();
       
        // 设置图片URL，确保路径正确
        if ($productImage && !empty($productImage['image_url'])) {
            $imageUrl = $productImage['image_url'];
            // 如果是完整URL，直接使用
            if (preg_match('/^https?:\/\//', $imageUrl)) {
                $row['image'] = $imageUrl;
            } else {
                // 处理相对路径
                if (substr($imageUrl, 0, 1) !== '/') {
                    // 如果不以/开头，可能是相对于uploads的路径
                    if (strpos($imageUrl, 'uploads/') === 0) {
                        $imageUrl = '/' . $imageUrl;
                    } else {
                        $imageUrl = '/uploads/' . $imageUrl;
                    }
                } else {
                    // 已经是绝对路径，直接使用
                }
                $row['image'] = $this->request->domain() . $imageUrl;
            }
        } else {
            $row['image'] = '';
        }
        
        // 处理时间格式
        $row['createtime'] = $row['createtime'] ? date('Y-m-d H:i:s', $row['createtime']) : '';
        $row['updatetime'] = $row['updatetime'] ? date('Y-m-d H:i:s', $row['updatetime']) : '';
        
        // 确保merchant_store_name字段存在
        if (!isset($row['merchant_store_name']) || empty($row['merchant_store_name'])) {
            $row['merchant_store_name'] = '未知商家';
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看未通过原因
     */
    public function rejectReason($ids = null)
    {
        $row = Db::name('product')
            ->field('id, name, reject_reason')
            ->where('id', $ids)
            ->find();
            
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 审核操作
     */
    public function audit($ids = null)
    {
        $row = Db::name('product')->where('id', $ids)->find();
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            
            // 开启事务
            Db::startTrans();
            try {
                $updateData = [
                    'updatetime' => time(),
                    'audit_time' => time(),
                    'auditor_id' => $this->auth->id
                ];
                
                // 根据审核结果设置状态
                if ($params['status'] == 1) {
                    // 审核通过
                    $updateData['audit_status'] = 1;  // 审核通过
                    $updateData['shelf_status'] = 1;  // 自动上架
                } elseif ($params['status'] == 0) {
                    // 审核不通过
                    $updateData['audit_status'] = 0;  // 审核未通过
                    $updateData['shelf_status'] = 0;  // 下架
                    if (isset($params['reject_reason']) && !empty($params['reject_reason'])) {
                        $updateData['reject_reason'] = $params['reject_reason'];
                    }
                }
                
                // 更新商品状态
                $result = Db::name('product')
                    ->where('id', $ids)
                    ->update($updateData);
                
                if ($result === false) {
                    throw new \Exception('更新商品状态失败');
                }
                
                // 提交事务
                Db::commit();
                $this->success();
                
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        $this->view->assign('statusList', [
            '1' => __('审核通过'),
            '0' => __('审核不通过')
        ]);
        return $this->view->fetch();
    }

    /**
     * 批量审核通过
     */
    public function approve($ids = null)
    {
        if ($ids) {
            // 处理单个ID和数组ID
            if (!is_array($ids)) {
                $ids = [$ids];
            }
            $list = Db::name('product')->where('id', 'in', $ids)->where('audit_status', 2)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $product) {
                    // 更新商品状态为审核通过并上架
                    $result = Db::name('product')
                        ->where('id', $product['id'])
                        ->update([
                            'audit_status' => 1, // 审核通过
                            'shelf_status' => 1, // 上架
                            'updatetime' => time()
                        ]);
                    if ($result) {
                        $count++;
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量审核拒绝
     */
    public function reject($ids = null)
    {
        if ($this->request->isPost()) {
            $reason = $this->request->post('reject_reason', '');
            if (empty($reason)) {
                $this->error('请填写拒绝原因');
            }
            
            if ($ids) {
                // 处理单个ID和数组ID
                if (!is_array($ids)) {
                    $ids = [$ids];
                }
                $list = Db::name('product')->where('id', 'in', $ids)->where('audit_status', 2)->select();

                $count = 0;
                Db::startTrans();
                try {
                    foreach ($list as $product) {
                        
                        // 更新商品状态为审核未通过并下架，并记录拒绝原因
                        $result = Db::name('product')
                            ->where('id', $product['id'])
                            ->update([
                                'audit_status' => 0, // 审核未通过
                                'shelf_status' => 0, // 下架
                                'reject_reason' => $reason, // 记录拒绝原因
                                'updatetime' => time(),
                                'audit_time' => time(),
                                'auditor_id' => $this->auth->id
                            ]);
                        if ($result) {
                            $count++;
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($count) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        // 显示拒绝原因输入框
        $this->view->assign('ids', $ids);
        return $this->view->fetch('product_audit/reject');
    }
}